#include "src/TcpServer.h"
#include "src/Logger.h"
#include "src/TcpConnection.h"
#include "src/Timestamp.h"
#include "src/EventLoopThread.h"
#include <string>

class EchoServer
{
public:
  EchoServer(EventLoop* loop, const InetAddress& listenAddr, const std::string& name)
   : m_loop(loop)
   , m_server(loop, listenAddr, name)
  {
    m_server.setConnectionCallback(std::bind(&EchoServer::onConnection, this, std::placeholders::_1));
    m_server.setMessageCallback(std::bind(&EchoServer::onMessage, this, 
    std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));

    m_server.setThreadNum(3);
  }
  void start() {
    m_server.start();
  }
private:
  void onConnection(const TcpConnectionPtr& conn)
  {
    if (conn->connected()) {
      LOG_INFO("Connection UP: %s", conn->peerAddress().toIpPort().c_str());
    } else {
      LOG_INFO("Connection DOWN: %s", conn->peerAddress().toIpPort().c_str());
    }
  }

  void onMessage(const TcpConnectionPtr& conn,
                  Buffer* buf,
                  Timestamp receiveTime)
  {
    std::string msg(buf->retrieveAllToString());
    conn->send(msg);
    conn->shutdown();
  }
private:
  EventLoop* m_loop;
  TcpServer m_server;
};

int main()
{
  EventLoop loop;
  
  InetAddress listenAddr(8080);
  
  EchoServer server(&loop, listenAddr, "EchoServer01");
  
  server.start();
  loop.loop();  // 启动 mainLoop
  return 0;
}